<?php

namespace app\api\controller;
use app\admin\model\commission\Log;
use app\admin\model\CouponRecord;
use app\admin\model\Details;
use app\admin\model\order\Feedback;
use app\admin\model\order\Operations;
use app\admin\model\Products;
use app\admin\model\Worktags;
use app\api\middleware\RoleCheck;
use app\api\service\OrderService;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Db;
use think\Request;
use think\Validate;

/**
 * 优惠券
 */
class Order extends Api
{
    protected $noNeedLogin = ['pay','ceshi'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
        $this->model=new \app\admin\model\Order;
    }

    /*
     * 添加订单
     */
    public function createOrder()
    {
        $service = new OrderService();
        $param=$this->request->post();
        $param['user_id']=$this->auth->id;
        $order = $service->createOrder($param);
        $this->success('请求成功', [
            'id' => $order,
        ]);
    }



    /**
     * 获取支付信息
     */
    public function getPayment()
    {
        if (!$id = input('id/d')) {
            $this->error('订单ID不能为空');
        }
        $payment = OrderService::getPayment($id, $this->auth->id);
        $this->success('请求成功', [
            'payment' => $payment,
        ]);
    }


    //立即支付

    public function immediate_payment()
    {
        if (!$id = input('id/d')) {
            $this->error('订单ID不能为空');
        }
        $order_no = order_no();
        //重置订单号
        $result=\app\admin\model\Order::where('id','=',$id)->where('order_status','=',0)->update(['order_no'=>$order_no]);
        if($result===0){
            $this->error('当前订单已支付');
        }
        $payment = OrderService::getPayment($id, $this->auth->id);
        $this->success('请求成功', [
            'payment' => $payment,
        ]);
    }


    /*
     * 用户订单列表
     */

    public function order_list(){

        $query = $this->model
            ->where('user_id', '=', $this->auth->id)
            ->field('id,order_no, amount, order_status, FROM_UNIXTIME(createtime, \'%Y-%m-%d %H:%i:%s\') as createtime, goodname, goodimage')
            ->order('id desc');
        $order_status= input('order_status');
        if ($order_status!=null&&$order_status!="") {
            $query->where('order_status', '=', $order_status);
        }
        $list = $query->paginate(10);
        $this->success(['请求成功'],$list);
    }

    /*
     * 订单详情
     */
    public function order_detail(){
        if(!$id= input('id')){
            $this->error('请选择订单');
        }

        $info = $this->model->where('id',$id)->field('pay_time,refund_time,goodid,address,goodtype,riderid,id,pay_type,order_status,goodname,goodimage,receiv_time,pay_type,amount,coupon_amount,paid_amount,order_no,createtime,expire_pay_time,riderid,message')->find();
        if(!$info){
            $this->error('订单不存在');
        }
        if($info['order_status']==0){
            $remaining_seconds = $info['expire_pay_time'] - time();
            $info['seconds'] = max(0, $remaining_seconds);
        }

        if($info['createtime']){
            $info['createtime'] = date('Y-m-d H:i:s', $info['createtime']);
        }
        if($info['refund_time']){
            $info['expire_pay_time'] = date('Y-m-d H:i:s', $info['refund_time']);
        }
        if($info['receiv_time']){
            $info['receiv_time'] = date('Y-m-d H:i:s', $info['receiv_time']);
        }
        if($info['pay_time']){
            $info['pay_time_time'] = date('Y-m-d H:i:s', $info['pay_time']);
        }

        if($info['riderid']!=null){
            $rider = Details::where('id','=',$info['riderid'])->field('id,name,img,age,lev,intro,work_experience,job_tags')->find();
            if(isset($rider['job_tags'])){
                $rider['job_tags']=Worktags::where('id','in',$rider['job_tags'])->field('id,name')->select();
            }
            $info['rider']=$rider;
        }
        $this->success(['请求成功'],$info);
    }

    //再来一单
    public function again_order()
    {
        if (!$id = input('id')) {
            $this->error('请选择订单');
        }
        $info = db::name('order')->where('id', $id)->field('goodid,goodtype,amount,goodname,goodimage')->find();
        $this->success(['请求成功'], $info);


    }


    //陪伴师获取订单列表
    public function rider_list(){
        //验证身份
        RoleCheck::role($this->auth->id,'companion');
        $list = $this->model
            ->where('riderid', '=', $this->auth->id)
            ->field('id,order_no, amount, order_status, FROM_UNIXTIME(createtime, \'%Y-%m-%d %H:%i:%s\') as createtime')
            ->order('id desc')
            ->paginate(10);
        foreach ($list as $row) {
            $log = Log::where('order_id', $row->id)->find();
            $row->rate = $log['rate'];
            $row->money = $log['money'];
            //查询用户
            $user=\app\admin\model\User::where('id',$row['user_id'])->find();
            $user=\app\admin\model\User::where('id',$row['user_id'])->find();
            $user=\app\admin\model\User::where('id',$row['user_id'])->find();
        }

        $this->success(['请求成功'],$list);
    }



    //陪伴师 订单列表  代理和经销商通用

    public function agent_order()
    {
        $user = Details::where('user_id', '=', $this->auth->id)->where('login_status', '=', '正常')
            ->find();
        // 检查用户角色
        if (!$user) {
            fail('用户不存在或登录状态异常');
        }
        $role = $user['role'];
        $order_status= input('order_status');
        if($order_status!=null&&$order_status!=""){
            $query = \app\admin\model\Order::where('order_status', '=', $order_status);
        }else{
            $query = \app\admin\model\Order::where('order_status', 'in', [1, 2]);
        }

        $querytj = \app\admin\model\Order::where('order_status', 'in',  [1, 2]);


        $startDateTime= input('startDateTime');
        $endDateTime= input('endDateTime');
        if($startDateTime!=null&&$endDateTime!=null){
            $query->whereBetween('createtime', [strtotime($startDateTime.' 00:00:00'), strtotime($endDateTime.' 23:59:59')]);
            $querytj->whereBetween('createtime', [strtotime($startDateTime.' 00:00:00'), strtotime($endDateTime.' 23:59:59')]);
        }

        // 查询获取符合条件的用户ID
        $query->whereIn('id', function ($subQuery) use ($user) {
            $subQuery->table('fa_commission_log')
                ->where('user_id', '=', $user['user_id'])
                ->field('order_id');
        });

        $querytj->whereIn('id', function ($subQuery) use ($user) {
            $subQuery->table('fa_commission_log')
                ->where('user_id', '=', $user['user_id'])
                ->field('order_id');
        });

        $ordertj = $querytj->select();
        $total=0;//总数
        $ing=0;//进行中
        $com=0;//已完成
        foreach ($ordertj as $k => $v) {
            if($v['order_status']==1){
                $ing++;
            }
            if($v['order_status']==2){
                $com++;
            }
            $total++;
        }
        // 执行查询并获取结果
        $orders = $query->field('is_reach,createtime,id,riderid,order_no,paid_amount,order_status,com_time,receiv_time,(select nickname from fa_user where fa_user.id=user_id)nickname')->order('id desc')->select();
        foreach ($orders as $k => $v) {

           $log= Log::where('order_id','=',$v['id'])->where('role','=',$role)->find();
            $orders[$k]['money']=$log!=null?$log['money']:0;
            $orders[$k]['rate']=$log!=null?$log['rate']:0;

            if($v['riderid']!=null&&$v['riderid']!=''){
                $rider = Details::where('id', '=',$v['riderid'])->find();
                $rider_user= \app\admin\model\User::where('id', '=',$rider['user_id'])->find();
                if($rider_user['agent_id']!=null){
                    $agent_user= Details::where('user_id', '=',$rider_user['agent_id'])->find();
                }elseif ($rider_user['room_id']!=null){
                    $agent_user= Details::where('user_id', '=',$rider_user['room_id'])->find();
                }else{
                    $agent_user['name']='无';
                }
                $orders[$k]['p_name']=$agent_user['name'];
                $orders[$k]['rider']=$rider['name'];
                if( $v['receiv_time']!=null){
                    $orders[$k]['receiv_time_text'] = date('Y-m-d', $v['receiv_time']);
                }
                if( $v['com_time']!=null){
                    $orders[$k]['com_time_text'] = date('Y-m-d',$v['com_time']);
                }
                $orders[$k]['createtime_text'] = date('Y-m-d',$v['createtime']);
            }
            if($v['order_status']==1){
                $orders[$k]['order_status']=$v['is_reach'];
            }
        }
        $data['ing']=$ing;
        $data['total']=$total;
        $data['com']=$com;
        $data['data']=$orders;
        $this->success(['请求成功'], $data);
    }

    //取消订单
    public function cancel_order(){
        if(!$id= input('id')){
            $this->error('请选择订单');
        }
        $info = $this->model->where('id',$id)->find();
        if($info['order_status']!=0){
            $this->error('订单已支付，无法取消');
        }
        $result = $this->model->where('id',$id)->update(['order_status'=>3,'memo'=>'用户取消','refund_time'=>time()]);
        if($result>0){
            $service = new OrderService();
            $service->return_co_av($id);
            // 订单操作记录
            Operations::create([
                'order_id' => $id,
                'action' => '取消订单',
                'user_id' => $info['user_id'],
                'description' => '用户取消订单',
                'created_at' => time(),
                'updated_at' => time(),
            ]);
            $this->success(['请求成功'], []);
        }else{
            $this->error('请求失败');
        }
    }

    //订单反馈
    public function order_feedback()
    {
        $user = RoleCheck::role($this->auth->id, 'companion');

        $order = \app\admin\model\Order::where('id', '=', input('order_id'))->find();
        if ($order['is_pj']==1) {
            $this->error('请勿重复评价');
        }
        if ($order['order_status']!=2) {
            $this->error('该订单未完成');
        }
        if( input('parent_feedback')==""){
            $this->error('请填写家长反馈');
        }
        if( input('content')==""){
            $this->error('请填写学习内容');
        }
        if( input('praise')==""){
            $this->error('请填写表扬内容');
        }

        Feedback::create([
            'order_id' => input('order_id'),
            'parent_feedback' => input('parent_feedback'),
            'content' => input('content'),
            'praise' => input('praise'),
            'improvement' => input('improvement'),
            'habits' => input('habits'),
            'parent_opinion' => input('parent_opinion'),
            'rating' => input('rating')
        ]);

      $result=  \app\admin\model\Order::where('id', '=', input('order_id'))->Update(['is_pj' => 1]);
      if($result>0){
          $this->success('请求成功', []);
      }else{
          $this->error('请求失败');
      }
    }

    public function ceshi(){
        $OrderService=new OrderService();
        $OrderService->fenyong(99);
    }

    public function  expire_pay_time(){
        $order = \app\admin\model\Order::where('id', '=', input('order_id'))->find();
        $expire_pay_time=$order['expire_pay_time'];
        $lefttime=$expire_pay_time-time();
        $this->success('请求成功',['lefttime'=>$lefttime]);
    }
}
